﻿using ConfExpert.Forms.Base;
using ConfExpert.Properties;
using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraTab;
using DevTeam;

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo
{
    public partial class Du4KesimV3 : XForm
    {
        public Du4KesimV3()
        {
            InitializeComponent();
        }

        //BindingSource bsKesimEmri;
        //DataTable dt;

        string headerDosya = "Kesim föylerinin barkodlarını okutun.";
        string headerList = "Keseceğiniz kumaşa çift tıklayın.";
        string headerTop = "Topun barkodunu okutun.";

        List<XtraTabPage> BarkodEnabledTab = new List<XtraTabPage>();

        private void Du4_Load(object sender, EventArgs e)
        {
            BarkodEnabledTab.Add(tabDosya);
            BarkodEnabledTab.Add(tabKesim);
            BarkodEnabledTab.Add(tabTop);

            tabs.SelectedTabPage = tabList;

            this.Text = "Du4 Kesim";

            this.BarcodeRead_done += new BarCode_Read(Du4Kesim_BarcodeRead_done);
            Bind();
            PopupMenu popupEksik = new PopupMenu(barManager);
            popupEksik.Name = "Sepet";
            foreach (string str in "En az bir kumaşı kesilmeyen;Anabedeni kesilmeyen;Garni 1'i kesilmeyen;Garni 2'si kesilmeyen;Garni 3'ü kesilmeyen;Tüm kayıtlar".Split(';'))
            {
                BarButtonItem bbi = new BarButtonItem(barManager, str, 0, BarShortcut.Empty);
                bbi.GroupIndex = 2;
                bbi.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Default;
                bbi.Appearance.Font = new System.Drawing.Font(bbi.Appearance.Font.FontFamily, (float)13);
                bbi.ItemClick += new ItemClickEventHandler(bbi_ItemClick);
                popupEksik.AddItem(bbi);
            }

            ddeEksik.DropDownControl = popupEksik;
            tabs.ShowTabHeader = DefaultBoolean.False;

            gvKesimEmri.CustomUnboundColumnData += new DevExpress.XtraGrid.Views.Base.CustomColumnDataEventHandler(gvProduct_CustomUnboundColumnData);
            gvKesimEmri.RowCellClick += new RowCellClickEventHandler(gridview_RowCellClick);
            gvKesimEmri.DoubleClick += new EventHandler(gvKesimEmri_DoubleClick);

            gvKesilecek.RowStyle += new RowStyleEventHandler(gvKesilecek_RowStyle);
            gvTop.RowStyle += new RowStyleEventHandler(gvTop_RowStyle);
            gvKesimEmri.RowStyle += new RowStyleEventHandler(gvKesimEmri_RowStyle);

            gvKesimEmri.BestFitColumns();

            if (ytk(131))
                gvTop.Click += new EventHandler(gvTop_Click);
        }

        void gvKesimEmri_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (gvKesimEmri.GetRowCellValue(e.RowHandle, "Sec") != null && (bool)gvKesimEmri.GetRowCellValue(e.RowHandle, "Sec"))
            {
                e.Appearance.BackColor = Color.Khaki;
            }
        }

        void gvTop_Click(object sender, EventArgs e)
        {
            int rollId = (gvTop.GetFocusedDataRow()["RollId"]).ToInt();

            BarcodeRead_done(rollId);

            gvTop.FocusedRowHandle = gvTop.LocateByValue("RollId", rollId);
            gvTop.MakeRowVisible(gvTop.FocusedRowHandle);
            gvTop.RefreshData();
        }

        void gvTop_RowStyle(object sender, RowStyleEventArgs e)
        {
            var oRollId = gvTop.GetRowCellValue(e.RowHandle, "RollId");
            if (oRollId != null && (int)oRollId == activeRollId)
            {
                e.Appearance.BackColor = Color.YellowGreen;
            }
        }

        void gvKesilecek_RowStyle(object sender, RowStyleEventArgs e)
        {
            var pID = gvKesilecek.GetRowCellValue(e.RowHandle, "ProductId");
            if (pID != null && pID != DBNull.Value && (int)pID == activeProduct)
            {
                e.Appearance.BackColor = Color.YellowGreen;
            }
        }

        int activeProduct = -1;

        void bbi_ItemClick(object sender, ItemClickEventArgs e)
        {
            barCode = string.Empty;
            bool tumu = ddeEksik.Text.ToLower().Contains("tüm");

            switch (e.Item.Caption)
            {
                case "Anabedeni kesilmeyen":
                    gvKesimEmri.ActiveFilterString = string.Format("{0} = 'Eksik'", "A");
                    break;
                case "Garni 1'i kesilmeyen":
                    gvKesimEmri.ActiveFilterString = string.Format("{0} = 'Eksik'", "G1");
                    break;
                case "Garni 2'si kesilmeyen":
                    gvKesimEmri.ActiveFilterString = string.Format("{0} = 'Eksik'", "G2");
                    break;
                case "Garni 3'ü kesilmeyen":
                    gvKesimEmri.ActiveFilterString = string.Format("{0} = 'Eksik'", "G3");
                    break;
                default:
                    gvKesimEmri.ActiveFilterString = "";
                    break;
            }
        }

        private void CreateKPI(GridView gv, string colName)
        {
            RepositoryItemImageComboBox imageCombo = gv.GridControl.RepositoryItems.Add("ImageComboBoxEdit") as RepositoryItemImageComboBox;
            imageCombo.Items.BeginUpdate();
            imageCombo.SmallImages = imgIndicators;

            imageCombo.Items.Add(new ImageComboBoxItem("Tamamlandı", true, 0));
            imageCombo.Items.Add(new ImageComboBoxItem("Eksik", false, 3));

            imageCombo.GlyphAlignment = DevExpress.Utils.HorzAlignment.Center;
            imageCombo.Items.EndUpdate();
            gv.Columns[colName].ColumnEdit = imageCombo;
        }

        private bool Erkek
        {
            get
            {
                return !btnBedenDagilimi.Text.ToLower().Contains("erkek");
            }
        }


        //DataSet dsKesimEmri = null;
        private void Bind()
        {
            //dsKesimEmri = Session.DataManager.ExecuteDataSet("GetDu4KesimEmri", Erkek);
            //bsKesimEmri = new BindingSource(dsKesimEmri, dsKesimEmri.Tables[0].TableName);
            //InitGridView(gvKesimEmri, bsKesimEmri);

            gvKesimEmri.Init("GetDu4KesimEmri", Erkek);
            FormatGv(gvKesimEmri);
        }

        //BindingSource bsRolls;
        string latestKPICol = string.Empty;
        string idxs = string.Empty;

        void gvKesimEmri_DoubleClick(object sender, EventArgs e)
        {
            barCode = string.Empty;
            GridColumn gc = gvKesimEmri.FocusedColumn;
            string colName = gc.FieldName.Remove(gc.FieldName.Length - 1, 1);
            if (gvKesimEmri.FocusedRowHandle > -1 && (colName == "ProductId" || colName == "Garni1" || colName == "Garni2" || colName == "Garni3"))
            {
                switch (colName)
                {
                    case "ProductId":
                        latestKPICol = "A";
                        break;
                    case "Garni1":
                        latestKPICol = "G1";
                        break;
                    case "Garni2":
                        latestKPICol = "G2";
                        break;
                    case "Garni3":
                        latestKPICol = "G3";
                        break;
                }

                DataRow drDoubleClicked = gvKesimEmri.GetDataRow(gvKesimEmri.FocusedRowHandle);

                var Id = drDoubleClicked[colName];

                if (Id != DBNull.Value)
                {
                    //DataSet ds = Session.DataManager.ExecuteDataSet("GetAllRollsByProductId", Id);
                    //pic.Visible = true;
                    //lblBarkod.Visible = true;

                    //DataTable dt = Session.DataManager.ExecuteDataTableByQuery("select Photo from V_ProductPhoto where productId = " + Id.ToString());
                    //if (dt.Rows.Count > 0)
                    //{
                    //    byte[] img = (byte[])dt.Rows[0][0];
                    //    MemoryStream ms = new MemoryStream(img);
                    //    pic.Image = Image.FromStream(ms);
                    //}
                    //else
                    //{
                    //    pic.Image = null;
                    //}

                    if (SelectedRows.Rows.Count > 1)
                    {
                        idxs = string.Empty;

                        int productCount = SelectedRows.Select(colName + " <> " + Id).Length;
                        if (productCount > 0)
                        {
                            ShowMessage("Toplu kesim yapabilmek için tıkladığınız sütundaki kumaşların aynı olması gerekir!");
                            return;
                        }
                        else
                        {
                            #region Toplu Kesim

                            string modelNos = string.Empty;
                            string orderNos = string.Empty;
                            string pas = string.Empty;
                            string dosyaNos = string.Empty;

                            foreach (DataRow drIdx in SelectedRows.Rows)
                            {
                                idxs += drIdx["idx"].ToString() + ",";

                                string strModelNo = drIdx["Model"].ToString();
                                if (!modelNos.Contains(strModelNo))
                                    modelNos += strModelNo + ",";

                                string strOrderNo = drIdx["OrderNo"].ToString();
                                if (!orderNos.Contains(strOrderNo))
                                    orderNos += strOrderNo + ",";

                                string strPa = drIdx["PA"].ToString();
                                if (!pas.Contains(strPa))
                                    pas += strPa + ",";

                                string strDosyaNo = drIdx["DosyaNo"].ToString();
                                if (!dosyaNos.Contains(strDosyaNo))
                                    dosyaNos += strDosyaNo + ",";
                            }

                            idxs = idxs.Remove(idxs.Length - 1);

                            SetMultiLineText(idxs, lblIdx, "idx");
                            SetMultiLineText(modelNos, lblModelNo, "model");
                            SetMultiLineText(orderNos, lblOrderNo, "sipariş no");
                            SetMultiLineText(pas, lblPA, "PA");
                            SetMultiLineText(dosyaNos, lblDosyaNo, "dosya no");

                            activeProduct = (int)drDoubleClicked[colName];

                            tabs.SelectedTabPage = tabKesim;

                            //string artikel = ds.Tables[0].Rows[0][1].ToString();
                            //txtInfo.Caption = artikel;
                            //gvTop.Init(ds.Tables[1]);

                            //bsRolls = new BindingSource(ds, ds.Tables[1].TableName);
                            //InitGridView(gvTop, bsRolls);

                            DataSet dsBD = Session.DataManager.ExecuteDataSet("GetDu4KesilenAdetToplu", idxs.ToString());
                            DataTable dtBD = ClearUnusedCols(dsBD.Tables[0]);
                            dsBD.Tables.RemoveAt(0);
                            dsBD.Tables.Add(dtBD);

                            BindingSource bsBD = new BindingSource(dsBD, dtBD.TableName);
                            InitGridView(gvBD, bsBD);

                            #endregion
                        }
                    }
                    else
                    {
                        #region Tekil Kesim
                        string modelNo = drDoubleClicked["Model"].ToString();
                        string pa = drDoubleClicked["PA"].ToString();
                        string orderNo = drDoubleClicked["OrderNo"].ToString();
                        int idx = (int)drDoubleClicked["idx"];
                        idxs = idx.ToString();
                        string dosyaNo = drDoubleClicked["DosyaNo"].ToString();
                        //string artikel = ds.Tables[0].Rows[0][1].ToString();

                        activeProduct = (int)drDoubleClicked[colName];

                        lblModelNo.Text = modelNo;
                        lblDosyaNo.Text = dosyaNo;
                        lblPA.Text = pa;
                        lblOrderNo.Text = orderNo;

                        tabs.SelectedTabPage = tabKesim;

                        //txtInfo.Caption = artikel;
                        lblIdx.Text = idx.ToString();

                        //bsRolls = new BindingSource(ds, ds.Tables[1].TableName);
                        //InitGridView(gvTop, bsRolls);

                        DataSet dsBD = Session.DataManager.ExecuteDataSet("GetDu4KesilenAdet", idx);
                        DataTable dtBD = ClearUnusedCols(dsBD.Tables[0]);
                        dsBD.Tables.RemoveAt(0);
                        dsBD.Tables.Add(dtBD);

                        BindingSource bsBD = new BindingSource(dsBD, dtBD.TableName);
                        InitGridView(gvBD, bsBD);

                        #endregion
                    }

                    //DataSet dsStatus = Session.DataManager.ExecuteDataSet("GetDu4ProductStatusToplu3", idxs);
                    //BindingSource bsStatus = new BindingSource(dsStatus, dsStatus.Tables[0].TableName);
                    //InitGridView(gvKesilecek, bsStatus);

                    gvKesilecek.Init("GetDu4ProductStatusToplu3", idxs, latestKPICol);
                    gvKesilecek.AddDetailGrid(gvDiger, "ProductId", 1);
                    gvKesilecek.AddDetailGrid(gvTop, "ProductId", 2);

                    gvKesilecek.AddColumn("Diğer İhtiyaç", typeof(decimal), "SUM(Child({FK}).Tahmini)");
                    gvKesilecek.MakeColumnInvisible("PRO");

                    FormatGv(gvBD);
                    FormatGv(gvKesilecek);
                    FormatGv(gvTop);
                    FormatGv(gvDiger);
                    CreateKPI(gvDiger, "D");

                    gvTop.FormatAsNumber(1, "Qty");
                    //gvTop.AddSummary("Qty");
                    gvKesilecek.FocusedRowHandle = gvKesilecek.LocateByValue("ProductId", activeProduct);
                    gvTop.Columns["RollId"].MinWidth = 75;
                }
            }
        }

        private void SetMultiLineText(string text, LabelControl lbl, string caption)
        {
            string[] arr = text.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (arr.Length > 1)
                lbl.Text = arr.Length.ToString() + " farklı " + caption;
            else
                lbl.Text = text;
        }


        DataTable ClearUnusedCols(DataTable dt)
        {
            string ignore = "modifiedon;idx";   //tip

            //dt.Rows.RemoveAt(1);
            string colNames = "";


            for (int i = 2; i < dt.Columns.Count; i++)
            {
                if (ignore.Contains(dt.Columns[i].ColumnName.ToLower()))
                {
                    continue;
                }

                if (dt.Rows[0][i].ToString() == "0" || dt.Rows[0][i].ToString() == "")
                {
                    colNames += dt.Columns[i].ColumnName + ";";
                }
                else
                    break;
            }

            for (int i = dt.Columns.Count - 1; i > 2; i--)
            {
                if (ignore.Contains(dt.Columns[i].ColumnName.ToLower()))
                {
                    continue;
                }

                if (dt.Rows[0][i].ToString() == "0" || dt.Rows[0][i].ToString() == "")
                {
                    colNames += dt.Columns[i].ColumnName + ";";
                }
                else
                    break;
            }

            foreach (string colName in colNames.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
            {
                dt.Columns.Remove(colName);
            }


            foreach (string colName in ignore.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
            {
                if (dt.Columns[colName] != null)
                    dt.Columns.Remove(colName);
            }


            foreach (DataColumn dc in dt.Columns)
            {
                string dcName = dc.ColumnName.ToLower();
                if (dcName != "tip")
                    if (!ignore.Contains(dcName))
                        dc.Caption = dcName.Substring(1, dcName.Length - 1);
            }

            return dt;

        }

        DataTable SelectedRows
        {
            get
            {
                DataTable dt = gvKesimEmri.DataTable();
                DataTable dtNew = dt.Clone();
                dt.Select("Sec=true").CopyToDataTable(dtNew, LoadOption.OverwriteChanges);
                return dtNew;
            }
        }

        void gridview_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            barCode = string.Empty;
            if (e.Column.FieldName == "Sec")
            {
                DataRow dr = gvKesimEmri.GetFocusedDataRow();   // ((DataRowView)bsKesimEmri.Current).Row;
                bool currentValue = (bool)dr["sec"];
                dr["Sec"] = !currentValue;
            }

            Notify(SelectedRows.Rows.Count.ToString());
        }

        Font FormFont = new Font("Calibri", 14, FontStyle.Regular);

        private void FormatGv(GridView gv)
        {
            gv.Appearance.HeaderPanel.Font = FormFont;
            gv.Appearance.Row.Font = FormFont;
            gv.OptionsView.EnableAppearanceOddRow = false;
            gv.OptionsView.EnableAppearanceEvenRow = false;
            //            gvTop.Appearance.FocusedRow.BackColor = Color.YellowGreen;

            gv.OptionsBehavior.ReadOnly = true;
            gv.OptionsBehavior.Editable = false;
            gv.OptionsSelection.EnableAppearanceFocusedCell = false;
            gv.OptionsView.ShowIndicator = false;

            if (gv.Name.Contains("KesimEmri"))
            {
                gvTop.OptionsView.ShowAutoFilterRow = true;
                //gv.OptionsSelection.EnableAppearanceFocusedCell = false;
                gv.OptionsBehavior.EditorShowMode = EditorShowMode.MouseDownFocused;

                gv.MakeColumnInvisible("ProductId", "Garni1", "Garni2", "Garni3");
                gv.MakeReadOnly();

                if (gv.Columns["ProductIdD"] != null)
                {
                    gv.Columns["ProductIdD"].AppearanceCell.Font = new Font(FormFont, FontStyle.Underline);
                    gv.Columns["Garni1D"].AppearanceCell.Font = new Font(FormFont, FontStyle.Underline);
                    gv.Columns["Garni2D"].AppearanceCell.Font = new Font(FormFont, FontStyle.Underline);
                    gv.Columns["Garni3D"].AppearanceCell.Font = new Font(FormFont, FontStyle.Underline);

                    gv.Columns["ProductIdD"].AppearanceCell.ForeColor =
                    gv.Columns["Garni1D"].AppearanceCell.ForeColor =
                    gv.Columns["Garni2D"].AppearanceCell.ForeColor =
                    gv.Columns["Garni3D"].AppearanceCell.ForeColor = Color.MediumBlue;
                }

                gvKesimEmri.Columns["Garni1"].ColumnEdit =
                gvKesimEmri.Columns["Garni2"].ColumnEdit =
                gvKesimEmri.Columns["Garni3"].ColumnEdit = RI(Rp.V_Kumas);

                CreateKPI(gvKesimEmri, "A");
                CreateKPI(gvKesimEmri, "G1");
                CreateKPI(gvKesimEmri, "G2");
                CreateKPI(gvKesimEmri, "G3");

                AddTooltip(gvKesimEmri, "A", "Anabeden Durumu");
                AddTooltip(gvKesimEmri, "G1", "Garni 1 Durumu");
                AddTooltip(gvKesimEmri, "G2", "Garni 2 Durumu");
                AddTooltip(gvKesimEmri, "G3", "Garni 3 Durumu");

                gvKesimEmri.OptionsSelection.EnableAppearanceFocusedCell = false;
                gvKesimEmri.BestFitColumns();
                gvKesimEmri.Columns["Scan"].Width = 40;

                gvKesimEmri.AddSummary();

                gvKesimEmri.Columns["Model"].Width = 150;
                gvKesimEmri.Columns["idx"].Width = 60;
            }
            else
                gv.OptionsView.ShowAutoFilterRow = false;

            gv.BestFitColumns();
        }

        int activeRollId = -1;
        void Du4Kesim_BarcodeRead_done(int barcode)
        {
            lblQty.Text = "0";
            if (tabs.SelectedTabPage == tabKesim)
            {
                //DataTable dtRoll = Session.DataManager.ExecuteDt("GetDu4Roll", barcode);
                DataRow[] drs = gvTop.DataTable().Select("RollId=" + barcode);

                if (drs.Length > 0)
                {
                    DataRow dr = drs[0];
                    activeRollId = (int)dr["RollId"];
                    lblTopId.Text = activeRollId.ToString();
                    lblQty.Text = dr["Qty"].ToString() + " mt.";
                    lblBarkod.Visible = false;
                }
                else
                {
                    txtInfo.Caption = "(" + barcode.ToString() + " ) Listedeki toplardan değil! Tekrar okutun ...";
                    barCode = string.Empty;
                }
            }
            else if (tabs.SelectedTabPage == tabDosya)
            {
                DataTable dt = Session.DataManager.ExecuteDataTable("GetDu4DosyaNoFiltre", barcode);
                foreach (DataRow dr in dt.Rows)
                {
                    txtDosyaNo.Text += dr[0].ToString() + "\r\n";
                }
            }
            else if (tabs.SelectedTabPage == tabTop)
            {
                DataTable dtRoll = Session.DataManager.ExecuteDataTable("GetDu4Roll", barcode);
                DataRow dr = dtRoll.Rows[0];
                lblKontrolArtikel.Text = dr["Product"].ToString();
                lblKontrolMK.Text = dr["MusteriKodu"].ToString();
                lblKontrolUK.Text = dr["UreticiKodu"].ToString();
                lblKontrolRollId.Text = dr["RollId"].ToString();
                lblKontrolQty.Text = dr["Qty"].ToString();
                MemoryStream ms = new MemoryStream((byte[])dr["PhotoLarge"]);
                TopKontolImg.Image = Image.FromStream(ms);
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            //TODO: idx sütununu düzenle
            if (lblIdx.Text == string.Empty || lblTopId.Text == string.Empty)
            {
                timer.Enabled = true;
                return;
            }
            else if (txtQty.Text == string.Empty || Convert.ToDecimal(txtQty.Text) == 0)
            {
                timerTxtQty.Enabled = true;
                return;
            }

            decimal qty = Convert.ToDecimal(txtQty.Text);
            decimal qtyInit = Convert.ToDecimal(lblQty.Text.Replace(" mt.", ""));

            if (qty <= qtyInit)
            {
                //DateTime latestDate = (DateTime)ds.V_Du4Cikan.Compute("max(KesilenTarih)", "");

                int rollId = int.Parse(lblTopId.Text);

                if (SelectedRows.Rows.Count > 1)
                {
                    Session.DataManager.ExecuteNonQuery("Du4TopKes2Toplu", idxs, rollId, qty);

                    foreach (string idx in idxs.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                        gvKesimEmri.DataTable().Select("idx=" + idx)[0][latestKPICol] = true;
                }
                else
                {
                    int idx = int.Parse(lblIdx.Text);
                    idxs = idx.ToString();

                    Session.DataManager.ExecuteNonQuery("Du4TopKes2", idx, rollId, qty);

                    gvKesimEmri.DataTable().Select("idx=" + lblIdx.Text)[0][latestKPICol] = true;
                }

                //DataSet dsStatus = Session.DataManager.ExecuteDataSet("GetDu4ProductStatusToplu3", idxs);
                //BindingSource bsStatus = new BindingSource(dsStatus, dsStatus.Tables[0].TableName);
                //InitGridView(gvKesilecek, bsStatus);
                gvKesilecek.RefreshDataSource(true, "GetDu4ProductStatusToplu3", idxs, latestKPICol);

                lblQty.Text = (qtyInit - qty).ToString("n1");

                txtInfo.Caption = String.Format("{0} Id'li toptan {1} mt. kesildi.", lblTopId.Text, txtQty.Text);

                gvTop.GetFocusedDataRow()["Qty"] = qtyInit - qty;
                txtQty.Text = string.Empty;
                lblTopId.Text = string.Empty;
            }
            else
                ShowErrorMessage("Kesilecek miktar, top uzunluğundan büyük olamaz !");
        }

        private void btnPad_Click(object sender, EventArgs e)
        {
            string val = ((SimpleButton)sender).Text;

            if (val == "," && txtQty.Text.Contains(","))
                return;

            txtQty.Text = txtQty.Text + val;
        }

        private void btnSil_Click(object sender, EventArgs e)
        {
            txtQty.Text = string.Empty;
        }


        private void btnAll_Click(object sender, EventArgs e)
        {
            if (lblTopId.Text == string.Empty)
            {
                timer.Enabled = true;
            }
            else
            {
                txtQty.Text = lblQty.Text.Replace(" mt.", "");
            }

        }

        private delegate void BarCode_Read(int barcode);
        private event BarCode_Read BarcodeRead_done;

        string barCode = string.Empty;

        private void Du4Kesim_KeyPress(object sender, KeyPressEventArgs e)
        {
            bool isDigit = Char.IsDigit(e.KeyChar);
            if (isDigit)
            {
                if (BarkodEnabledTab.Contains(tabs.SelectedTabPage))
                {
                    barCode += e.KeyChar.ToString();
                    if (barCode.Length == 8)
                    {
                        string realCode = barCode.Substring(0, 7);
                        if (realCode != string.Empty)
                        {
                            try
                            {
                                int rollId = Convert.ToInt32(realCode);
                                BarcodeRead_done(rollId);
                            }
                            catch (Exception)
                            {
                                barCode = string.Empty;
                            }
                        }

                        barCode = string.Empty;
                    }
                }
                else
                {
                    barCode = string.Empty;
                }
            }
            else
            {
                barCode = string.Empty;
            }
        }



        private void btnGuncelle_Click(object sender, EventArgs e)
        {
            Bind();
            barCode = string.Empty;
        }

        private void btnBedenDagilimi_Click(object sender, EventArgs e)
        {
            if (Erkek)
            {
                btnBedenDagilimi.Text = btnBedenDagilimi.Text.Replace("Bayan", "Erkek");
                btnBedenDagilimi.Image = Resources.Manx48;
            }
            else
            {
                btnBedenDagilimi.Text = btnBedenDagilimi.Text.Replace("Erkek", "Bayan");
                btnBedenDagilimi.Image = Resources.Womanx48;
            }

            Bind();
            barCode = string.Empty;
        }

        private void btnZoom_Click(object sender, EventArgs e)
        {
            bool zoomIn = btnZoom.Text.ToLower().Contains("sadece");

            if (zoomIn)
            {
                gvKesimEmri.ActiveFilterString = "[Sec] = True";
                btnZoom.Text = btnZoom.Text.Replace("Sadece Seçtiklerimi", "Tümünü");
                btnZoom.Image = Resources.Find_32x32;
            }
            else
            {
                gvKesimEmri.ActiveFilterString = "";
                btnZoom.Text = btnZoom.Text.Replace("Tümünü", "Sadece Seçtiklerimi");
                btnZoom.Image = Resources.Buyutecx48;
            }
            barCode = string.Empty;
        }

        private void tabs_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            barCode = string.Empty;
            if (tabs.SelectedTabPage == tabList)
            {
                pnlStep1.Visible = true;
                pnlStep2.Visible = false;
                pnlStep3.Visible = false;

                txtInfo.Caption = headerList;
                pic.Visible = false;
                gvKesimEmri.BestFitColumns();
                if (gvKesimEmri.Columns["Scan"] != null)
                    gvKesimEmri.Columns["Scan"].Width = 40;

            }
            else if (tabs.SelectedTabPage == tabKesim)
            {
                pnlStep2.Visible = true;
                pnlStep1.Visible = false;
                pnlStep3.Visible = false;
            }
            else if (tabs.SelectedTabPage == tabDosya)
            {
                pnlStep3.Visible = true;
                pnlStep1.Visible = false;
                pnlStep2.Visible = false;

                txtInfo.Caption = headerDosya;
            }

            else if (tabs.SelectedTabPage == tabTop)
            {
                pnlStep2.Visible = true;
                pnlStep1.Visible = false;
                pnlStep3.Visible = false;

                txtInfo.Caption = headerTop;
            }
        }

        private void btnGeri_Click(object sender, EventArgs e)
        {
            barCode = string.Empty;
            tabs.SelectedTabPage = tabList;

            DataTable dt = gvKesimEmri.DataTable();
            foreach (DataRow dr in dt.Rows)
            {
                dr["Sec"] = false;
            }
            //Artikelle tek tek kesiliyorsa her geri dön dendiğinde listenin sıfırlanması doğru mu??
        }

        private void btnGotoList_Click(object sender, EventArgs e)
        {
            barCode = string.Empty;
            tabs.SelectedTabPage = tabList;
            string[] dosyaNos = txtDosyaNo.Text.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            string filter = "";
            foreach (string dosyaNo in dosyaNos)
            {
                string currentFilter = dosyaNo.ToUpper();
                filter += "StartsWith([DosyaNo], '" + currentFilter + "') or ";
            }
            if (filter.Length > 0)
            {
                filter = filter.Substring(0, filter.Length - 4);
            }

            gvKesimEmri.ActiveFilterString = filter;
            gvKesimEmri.BestFitColumns();
            //gvKesimEmri.Columns["Scan"].Width = 40;

        }

        private void btnDosyaBarkod_Click(object sender, EventArgs e)
        {
            barCode = string.Empty;
            tabs.SelectedTabPage = tabDosya;
        }

        private void btnBarkodTemizle_Click(object sender, EventArgs e)
        {
            barCode = string.Empty;
            txtDosyaNo.Text = "";
        }



        int counter = 0;
        private void timer_Tick(object sender, EventArgs e)
        {
            counter++;
            if (counter == 1)
            {
                lblBarkod.ForeColor = Color.Yellow;
                lblBarkod.BackColor = Color.Black;
            }
            if (counter == 2)
            {
                lblBarkod.ForeColor = Color.Black;
                lblBarkod.BackColor = lblDosyaNo.BackColor;
                counter = 0;
                timer.Enabled = false;
            }
        }


        int counterTxtQty = 0;
        private void timerTxtQty_Tick(object sender, EventArgs e)
        {

            counterTxtQty++;
            if (counterTxtQty == 1)
            {
                txtQty.Text = "EKSİK ";
                txtQty.ForeColor = Color.Yellow;
                txtQty.BackColor = Color.Black;

            }
            if (counterTxtQty == 2)
            {
                txtQty.Text = "";
                txtQty.ForeColor = Color.Black;
                txtQty.BackColor = Color.White;
                counterTxtQty = 0;
                timerTxtQty.Enabled = false;
            }

        }

        private void btnTopOkut_Click(object sender, EventArgs e)
        {
            barCode = string.Empty;
            tabs.SelectedTabPage = tabTop;
        }
    }
}